package com.sh.ssao.lottery.config.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j
@Component
public class FileUploadUtil {
    @Value("${file.win.path}")
    private String wpath;// = "D:/TEST/";

    @Value("${file.linux.path}")
    private String lpath;// = "/home/tomcat/file/";

    private String os = System.getProperty("os.name");

    @Value("${file.ip}")
    private  String ip;
    /**
     * 上传文件封装
     * @param multipartFile
     * @param type 业务类型
     * 1供应商文件
     * 2采购文件
     * 3其他文件
     * @param businessId 业务id
     * @return
     */
    public Map fileUpload(MultipartFile multipartFile, String type, String businessId){

        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String temp = StrUtil.generatorDate();
        Map<String,String> map = new HashMap<>();
        String path = "";
        String pathTemp = "";

        // 文件保存路径
        String savePath = null;
        if (os.toLowerCase().startsWith("win")) {
            //Windows
            if (!"".equals(businessId)) {
                path =wpath + type+"/"+businessId+"/"+temp;
                pathTemp = type+"/"+businessId+"/"+temp;
            }else{
                path =wpath + type+"/"+temp;
                pathTemp = type+"/"+temp;
            }

        }else {
            //linux
            if (!"".equals(businessId)) {
                path = lpath + type+"/"+businessId+"/"+temp;
                pathTemp = type+"/"+businessId+"/"+temp;
            }else{
                path = lpath + type+"/"+temp;
                pathTemp = type+"/"+temp;
            }

        }
        // 判断文件是否为空
        if (StringUtils.isNotBlank(multipartFile.getOriginalFilename())) {
            try {
                File filepath = new File(path);
                if (!filepath.exists()){
                    filepath.mkdirs();
                }
                savePath = path+"/"+multipartFile.getOriginalFilename();
                map.put("fileurl",savePath);
                map.put("httpurl","http://"+ip+":8081/"+pathTemp+"/"+multipartFile.getOriginalFilename());
//                map.put("httpurl","http://127.0.0.1:8081/gzst/X-admin-v2.2/images/touxiang.png");
                // 转存文件
                multipartFile.transferTo(new File(savePath));
                log.debug("保存文件成功"+multipartFile.getOriginalFilename());
                return map;
            } catch (Exception e) {
                log.error("保存文件出错{}",e);
            }
        }
        return map;
    }

    /**
     * 删除文件
     * @param filePath
     */
    public void delFile(String filePath){
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 文件下载
     * @param file
     * @return
     */
    public static ResponseEntity<byte[]> buildResponseEntity(File file){
        byte[] body = null;
        ResponseEntity<byte[]> entity =null;
        try {
            InputStream is = new FileInputStream(file);
            body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchement;filename=" + file.getName());
            HttpStatus statusCode = HttpStatus.OK;
            entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        }catch (IOException e){
            e.printStackTrace();
        }
        return entity;
    }
}
